// pages/video/video.js
import PubSub from "pubsub-js";
import {
  getVideoCategoryList,
  getVideoGroup,
  getVideoTimelineRecommend
} from '../../api/index'

import {
  getSearchDefault,
} from '../../api/index'

Page({

  data: {
    interval: 5000,
    duration: 1000,
    circular: true,
    autoplay: false,
    indicatorDots: true,
    current: 0,
    placeholder: '',
    recordList: [],
    videoId: '',
    videoGroupList: [], //  所有视频分组列表
    videoUpdateTime: [], // 记录所有已播放视频的播放进度
    trigger: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
   onLoad(options) {
    this.getVideoTabsList()
    this.getSearchDetail()
    getVideoTimelineRecommend().then(res => {
      const { datas } = res
      datas.map((item,index) => {
        item.id = index++
        return item
      })
      this.setData({ videoGroupList: datas, videoId: datas[0].id})
    })
  },

  onSearchVideo(event){
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  async getSearchDetail(){
    const { data } = await getSearchDefault()
    this.setData({ placeholder: data.showKeyword })
  },

  async getVideoTabsList() {
    const  { data } = await getVideoCategoryList()
    this.setData({ recordList: data })
  },

  async switchTabsClick(e) {
    const { videoId } = this.data
    this.setData({ videoGroupList: [] });
    wx.showLoading({
      title: '加载中...',
    })
    const { index, info: { id } } =  e.currentTarget.dataset;
    this.setData({ videoId: id });
    const { datas } = id === 1002 ?
        await getVideoTimelineRecommend() : await getVideoGroup({ id });
    datas.map((item, index) => {
      item.id = index++
      return item
    })
    this.setData({ videoGroupList: datas, current: index })
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300,
    });
    wx.hideLoading()
  },

  onHandleTimeUpdate(event) {
    const { videoId, videoUpdateTime } = this.data;
    const currentVideoObject = { vid: videoId, currentTime:  event.detail.currentTime };
    const videoTimeObject = videoUpdateTime.find((item) => item.vid === videoId);
    if (videoTimeObject) {
        videoTimeObject.currentTime = event.detail.currentTime;
        if (videoTimeObject.currentTime === event.detail.duration) {
          videoUpdateTime.splice(videoUpdateTime.findIndex((item) => item.vid === videoTimeObject.vid), 1)
        }
    } else {
      videoUpdateTime.push(currentVideoObject);
    }
    this.setData({
      videoUpdateTime
    })
  },

  onHandlePlay(event) {
    const { videoUpdateTime } = this.data;
    this.vid = event.currentTarget.id;
    this.setData({ videoId: this.vid });
    this.videoContext = wx.createVideoContext(this.vid);
    const videoObject = videoUpdateTime.find((item) => item.vid === this.vid);
    videoObject && this.videoContext.seek(videoObject.currentTime);
    this.videoContext.play();
  }
})